package com.tmeone.erpone.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tmeone.erpone.entity.SMenu;
import com.tmeone.erpone.entity.SRole;
import com.tmeone.erpone.entity.SUser;
import com.tmeone.erpone.mapper.SUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private SUserMapper userMapper;


    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        SUser user = userMapper.selectOne(new QueryWrapper<SUser>().lambda().eq(SUser::getUserName, s));
        if(user == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        //查询用户的角色
        List<SRole> roles = userMapper.selectRolesByUsername(s);
        //查询用户的权限
        List<SMenu> permissions = userMapper.selectPermissionsByUsername(s);
        StringBuilder stringBuilder = new StringBuilder();
        roles.forEach(role -> stringBuilder.append("ROLE_" + role.getRoleName()+","));
        permissions.forEach(permission -> stringBuilder.append(permission.getMenuName()+","));
        if (stringBuilder.length()>0){
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        }

        //创建Security的User,包装账号、密码和权限
        User user1 =
                new User(user.getUserName(),user.getPassWord(),
                        AuthorityUtils.commaSeparatedStringToAuthorityList(stringBuilder.toString()));
        return user1;
    }
}
